package com.rybbaby.tss.platform.sysSchool.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import com.rybbaby.tss.platform.sysAdminUserJoinSysRole.entity.SysAdminUserJoinSysRole;
import com.rybbaby.tss.platform.sysAdminUserJoinSysRole.service.ISysAdminUserJoinSysRoleService;
import com.rybbaby.tss.platform.sysRole.entity.SysRole;
import com.rybbaby.tss.platform.sysRole.service.ISysRoleService;
import com.rybbaby.tss.platform.sysRoleGroup.entity.SysRoleGroup;
import com.rybbaby.tss.platform.sysRoleGroup.service.ISysRoleGroupService;
import com.rybbaby.tss.platform.sysSchool.entity.SysSchool;
import com.rybbaby.tss.platform.sysSchool.service.ISysSchoolService;
import org.apache.poi.util.StringUtil;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 雷春琼
 * @description 园所管理
 * @createDate 2017-08-09 上午11:00:39
 */
@Controller
@RequestMapping(value = "sysSchoolController")
public class SysSchoolController extends BaseController {

    @Autowired
    private ISysSchoolService sysSchoolService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;
    @Autowired
    private ISysRoleGroupService sysRoleGroupService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysAdminUserJoinSysRoleService sysAdminUserJoinSysRoleService;

    /**
     * 获取园所列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取园所列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "sysSchoolList", method = RequestMethod.POST)
    public ModelAndView sysSchoolList(SysSchool entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysSchoolListView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysSchool.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.addOrder(Order.desc("createTime"));
            PageBean pageBean = sysSchoolService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param targetDateId 接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到园所视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(@RequestParam(required = true) String targetDateId, @RequestParam(required = true) String serializeNum) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("sysSchoolEditView"));
        if (StringUtils.isNotBlank(targetDateId)) {
            SysSchool editEntity = this.sysSchoolService.get(targetDateId);
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
        } else {
            mav.addObject("editModel", "add");
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存园所对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(SysSchool entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                SysSchool destEntity = this.sysSchoolService.get(id);
                BeanUtils.copyProperties(entity, destEntity, "createTime", "updateTime","schoolContractCode","schoolCode");
                destEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                this.sysSchoolService.updateEntitiy(destEntity);
            } else {
                String schoolAccount = request.getParameter("schoolAccount");//园长账号
                String educationalAccount = request.getParameter("educationalAccount");//教务账号
                String accountPhone = request.getParameter("accountPhone");//园长联系方式
                String educationalPhone = request.getParameter("educationalPhone");//教务联系方式
                String userPassword = request.getParameter("userPassword");//教务和园长密码
                //保存园所信息
                Object loginUserId_obj = getLoginUserId();
                entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                entity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                entity.setCreateUserId(super.getLoginUser().getId());
                sysSchoolService.save(loginUserId_obj, entity, this.getSession().getId(), schoolAccount, educationalAccount, accountPhone, educationalPhone, userPassword);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.sysSchoolService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.sysSchoolService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 获取所有园所列表
     *
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestLog(content = "获取所有园所列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "sysSchoolAllList", method = RequestMethod.GET)
    public String sysSchoolAllList() {
        //获取当前登录者
        String adminUserName = super.getLoginUser().getUserName();
        DetachedCriteria dc = DetachedCriteria.forClass(SysSchool.class);
        List<SysSchool> data = new ArrayList<>();
        if (!adminUserName.equals("admin")) {
            String schoolId = super.getLoginUser().getSchoolId();
            dc.add(Restrictions.eq("id", schoolId));
        }
        data = this.sysSchoolService.findByDetached(dc);
        List<Map<String, Object>> newData = new ArrayList<>();
        data.forEach((school) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", school.getId());
            map.put("name", school.getSchoolName());
            newData.add(map);
        });
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        ajr.setData(newData.toArray());
        return ajr.jsonResponse(true);
    }


    /**
     * 验证园所名称
     *
     * @param schoolName 用户名
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证园所名称", save = true)
    @RequestMapping(value = "verificationSchoolName", method = RequestMethod.POST)
    public String verificationSchoolName(String schoolName, String id) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT COUNT(1) count FROM sys_school WHERE schoolName = ? ");
            if (id != null && id != "") {
                sql.append("AND id != '" + id + "'");
            }
            Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{schoolName});
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 验证园所合同编码
     *
     * @param contractNum 用户名
     * @return
     */
    @ResponseBody
    @RequestLog(content = "验证园所名称", save = true)
    @RequestMapping(value = "verificationContractNum", method = RequestMethod.POST)
    public String verificationContractNum(String contractNum, String id) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT COUNT(1) count FROM sys_school WHERE contractNum = ? ");
            if (id != null && id != "") {
                sql.append("AND id != '" + id + "'");
            }
            Map<String, Object> findOneForJdbc = sysAdminUserService.findOneForJdbc(sql.toString(), new Object[]{contractNum});
            return responseRemoteValidate(findOneForJdbc != null && !findOneForJdbc.isEmpty() && findOneForJdbc.containsKey("count") && (findOneForJdbc.get("count").toString()).equals("0"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
